package com.niedziela12.pai.sessionbeans;

import com.niedziela12.pai.ejb.dto.RoomDTO;
import com.niedziela12.pai.ejb.entities.Room;
import com.niedziela12.pai.ejb.room.endpoints.RoomEndpoint;
import com.niedziela12.pai.ejb.room.endpoints.RoomEndpointLocal;
import com.niedziela12.pai.ejb.room.facades.RoomFacadeLocal;
import com.niedziela12.pai.sessionbeans.util.JsfUtil;
import com.niedziela12.pai.sessionbeans.util.PaginationHelper;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "roomController")
@SessionScoped
public class RoomController implements Serializable {

    private RoomDTO current;
    private DataModel items = null;
    @EJB
    private RoomEndpointLocal roomEndpoint;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    
    @ManagedProperty(value = "#{hotelController}")
    private HotelController hotelController;

    @ManagedProperty(value = "#{userRights}")
    private UserRights userRights;
    
    @ManagedProperty(value = "#{reservationController}")
    private ReservationController reservationController;

    public void setReservationController(ReservationController reservationController) {
        this.reservationController = reservationController;
    }

    public void setUserRights(UserRights userRights) {
        this.userRights = userRights;
    }
    
    public RoomController() {
    }

    public void setHotelController(HotelController hotelController){
        this.hotelController = hotelController;
    }
    
    public RoomDTO getSelected() {
        if (current == null) {
            current = new RoomDTO();
            selectedItemIndex = -1;
        }
        return current;
    }
    
    public int getSelectedItemIndex() {
        return selectedItemIndex;
    }

    public PaginationHelper getPagination() {
        if (pagination == null || (hotelController != null && hotelController.getSelected().getId() != null)){
            pagination = new PaginationHelper(10) {
                private long hotelId = -1;
                private int hotelRoomCount = -1;
                @Override
                public int getItemsCount() {
                    if(hotelRoomCount > -1)
                        return hotelRoomCount;
                    return roomEndpoint.getRoomsCount();
                }

                @Override
                public DataModel createPageDataModel() {
                    if(hotelController != null && hotelController.getSelected().getId() != null){
                        if(hotelId == -1){
                            hotelId = hotelController.getSelected().getId();
                            hotelRoomCount = hotelController.getSelected().getRooms().size();
                            hotelController.destroySelection();
                        }
                        return new ListDataModel(roomEndpoint.getRoomsInHotel(hotelId));
                    }
                    else{
                        hotelRoomCount = -1;
                        return new ListDataModel(roomEndpoint.getRooms(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                    }
                }
            };
        }
        return pagination;
    }
    
    public String prepareList() {
        recreateModel();
        return userRights.isModerator() ? "moderatorListRooms" : "otherListRooms";
    }
    
    public String prepareView() {
        current = (RoomDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return userRights.isModerator() ? "moderatorViewRoom" : "otherViewRoom";
    }

    public String prepareCreate() {
        current = new RoomDTO();
        selectedItemIndex = -1;
        return "moderatorAddRoom";
    }
    
    public String create() {
        try {
            roomEndpoint.addNewRoom(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RoomCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (RoomDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "moderatorEditRoom";
    }

    public String update() {
        try {
            roomEndpoint.updateRoomInfo(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RoomUpdated"));
            return userRights.isModerator() ? "moderatorViewRoom" : "otherViewRoom";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    
    public String prepareNewReservation() {
        current = (RoomDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        prepareReservationFromView();
        return "clientAddReservations";
    }
    
    public String prepareReservationFromView(){
        reservationController.prepareCreate();
        if(getSelectedItemIndex() > -1){
            reservationController.getSelected().setRoom(getSelected());
            destroySelection();
        }
        return "clientAddReservations";
    }

    public String destroy() {
        current = (RoomDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "moderatorListRooms";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "moderatorViewRoom";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "moderatorListRooms";
        }
    }

    private void performDestroy() {
        try {
            roomEndpoint.deleteRoom(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RoomDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }
    
    public void destroySelection(){
        current = new RoomDTO();
        selectedItemIndex = -1;
    }

    private void updateCurrentItem() {
        int count = roomEndpoint.getRoomsCount();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = roomEndpoint.getRooms(selectedItemIndex, selectedItemIndex + 1).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return userRights.isModerator() ? "moderatorListRooms" : "otherListRooms";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return userRights.isModerator() ? "moderatorListRooms" : "otherListRooms";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(roomEndpoint.getAllRooms(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(roomEndpoint.getAllRooms(), true);
    }

    @FacesConverter(forClass = RoomDTO.class)
    public static class RoomControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            RoomController controller = (RoomController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "roomController");
            return controller.roomEndpoint.getRoom(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof RoomDTO) {
                RoomDTO o = (RoomDTO) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + RoomDTO.class.getName());
            }
        }
    }
}
